import Typography from '@mui/material/Typography';
import { useState, useCallback, useEffect } from 'react';
import { _tasks, _posts, _timeline } from 'src/_mock';
import { DashboardContent } from 'src/layouts/dashboard';
import { AnalyticsNews } from '../analytics-news';
import { AnalyticsTasks } from '../analytics-tasks';
import { AnalyticsOrderTimeline } from '../analytics-order-timeline';
import { AnalyticsWidgetSummary } from '../analytics-widget-summary';
import { AnalyticsTrafficBySite } from '../analytics-traffic-by-site';
import { AnalyticsCurrentSubject } from '../analytics-current-subject';
import { AnalyticsConversionRates } from '../analytics-conversion-rates';
import { CashBookTable } from '../../cashBook';
import { getLastEightMonths } from '../../../utils/moths';
import { Grid } from '@mui/material';
import { expensesStatements, queryReportRecentlyAmount } from '../../../api/cash-book';

export function OverviewAnalyticsView() {
  const [yearExpenses, setYearExpenses] = useState<number>(0);
  const [monthExpenses, setMothExpenses] = useState<number>(0);
  const [weekExpenses, setWeekExpenses] = useState<number>(0);
  const [quarterExpenses, setQuarterExpenses] = useState<number>(0);
  const [quarterList, setQuarterList] = useState([]);
  const [quarterNameList, setQuarterNameList] = useState([]);
  const [quarterPer, setQuarterPer] = useState(0);
  const [yearList, setYearList] = useState([]);
  const [yearNameList, setYearNameList] = useState([]);
  const [monthList, setMonthList] = useState([]);
  const [monthNameList, setMonthNameList] = useState([]);
  const [weekList, setWeekList] = useState([]);
  const [weekNameList, setWeekNameList] = useState([]);
  const [weekPer, setWeekPer] = useState(0);
  const [monthPer, setMonthPer] = useState(0);
  const [yearPer, setYearPer] = useState(0);

  // Get year expenses
  const getYearExpenses = () => {
    const params = {
      timeType: 'year',
      date: new Date(),
    };
    expensesStatements(params).then((result) => {
      setYearExpenses(result.data);
    });
  };

  // Get weekly list and calculate weekPer after
  const getWeekList = () => {
    const params = {
      object: {
        timeType: 'week',
      },
      pageSize: 8,
      pageNumber: 1,
    };
    queryReportRecentlyAmount(params).then((result) => {
      const res = result.data.list.reverse();
      setWeekList(res.map((item: any) => item.amount));
      setWeekNameList(res.map((item: any) => item.cycle));

      if (res.length >= 2) {
        setWeekPer((res[res.length-1].amount-res[res.length-2].amount)/ res[res.length-2].amount*100);
      }
    });
  };

  const getMonthList = () => {
    const params = {
      object: {
        timeType: 'month',
      },
      pageSize: 8,
      pageNumber: 1,
    };
    queryReportRecentlyAmount(params).then((result) => {
      const res = result.data.list.reverse();
      setMonthList(res.map((item: any) => item.amount));
      setMonthNameList(res.map((item: any) => item.cycle));

      if (res.length >= 2) {
        setMonthPer((res[res.length-1].amount-res[res.length-2].amount)/ res[res.length-2].amount*100);
      }
    });
  };
  const getQuarterList = () => {
    const params = {
      object: {
        timeType: 'quarter',
      },
      pageSize: 8,
      pageNumber: 1,
    };
    queryReportRecentlyAmount(params).then((result) => {
      const res = result.data.list.reverse();
      setQuarterList(res.map((item: any) => item.amount));
      setQuarterNameList(res.map((item: any) => item.cycle));

      if (res.length >= 2) {
        setQuarterPer((res[res.length-1].amount-res[res.length-2].amount)/ res[res.length-2].amount*100);
      }
    });
  };

  const getYearList = () => {
    const params = {
      object: {
        timeType: 'year',
      },
      pageSize: 8,
      pageNumber: 1,
    };
    queryReportRecentlyAmount(params).then((result) => {
      const res = result.data.list.reverse();
      setYearList(res.map((item: any) => item.amount));
      setYearNameList(res.map((item: any) => item.cycle));

      if (res.length >= 2) {
        setYearPer((res[res.length-1].amount-res[res.length-2].amount)/ res[res.length-2].amount*100);
      }
    });
  };

  // Get month expenses
  const getMonthExpenses = () => {
    const params = {
      timeType: 'month',
      date: new Date(),
    };
    expensesStatements(params).then((result) => {
      setMothExpenses(result.data);
    });
  };

  // Get quarter expenses
  const getQuarterExpenses = () => {
    const params = {
      timeType: 'quarter',
      date: new Date(),
    };
    expensesStatements(params).then((result) => {
      setQuarterExpenses(result.data);
    });
  };

  // Get week expenses
  const getWeekExpenses = () => {
    const params = {
      timeType: 'week',
      date: new Date(),
    };
    expensesStatements(params).then((result) => {
      setWeekExpenses(result.data);
    });
  };

  useEffect(() => {
    getMonthExpenses();
    getQuarterExpenses();
    getWeekExpenses();
    getYearExpenses();
    getWeekList();
    getMonthList();
    getQuarterList();
    getYearList();
  }, []); // Empty dependency means it will run only once or when year changes

  // @ts-ignore
  return (
    <DashboardContent maxWidth="xl">
      <Typography variant="h4" sx={{ mb: { xs: 3, md: 5 } }}>
        Hi, Welcome back 👋
      </Typography>

      <Grid container spacing={3}>
        <Grid item xs={12} sm={6} md={3}>
          <AnalyticsWidgetSummary
            title="年度花销"
            percent={yearPer}
            total={yearExpenses}
            icon={<img alt="icon" src="/assets/icons/glass/lanling-zhangdan.svg" />}
            chart={{
              categories: yearNameList,
              series: yearList,
            }}
          />
        </Grid>

        <Grid item xs={12} sm={6} md={3}>
          <AnalyticsWidgetSummary
            title="季度花销"
            percent={quarterPer}
            total={quarterExpenses}
            color="secondary"
            icon={<img alt="icon" src="/assets/icons/glass/a-bianzu91.svg" />}
            chart={{
              categories: quarterNameList,
              series: quarterList,
            }}
          />
        </Grid>

        <Grid item xs={12} sm={6} md={3}>
          <AnalyticsWidgetSummary
            title="本月花销"
            percent={monthPer}
            total={monthExpenses}
            color="warning"
            icon={<img alt="icon" src="/assets/icons/glass/yonghuzhangdan.svg" />}
            chart={{
              categories: monthNameList,
              series: monthList,
            }}
          />
        </Grid>

        <Grid item xs={12} sm={6} md={3}>
          <AnalyticsWidgetSummary
            title="本周花销"
            percent={weekPer}
            total={weekExpenses}
            color="error"
            icon={<img alt="icon" src="/assets/icons/glass/yinhangduizhangdan.svg" />}
            chart={{
              categories: weekNameList,
              series: weekList,
            }}
          />
        </Grid>

        <Grid item xs={12} md={6} lg={12}>
          <CashBookTable />
        </Grid>

        <Grid item xs={12} md={6} lg={8}>
          <AnalyticsConversionRates
            title="Conversion rates"
            subheader="(+43%) than last year"
            chart={{
              categories: ['Italy', 'Japan', 'China', 'Canada', 'France'],
              series: [
                { name: '2022', data: [44, 55, 41, 64, 22] },
                { name: '2023', data: [53, 32, 33, 52, 13] },
              ],
            }}
          />
        </Grid>

        <Grid item xs={12} md={6} lg={4}>
          <AnalyticsCurrentSubject
            title="Current subject"
            chart={{
              categories: ['English', 'History', 'Physics', 'Geography', 'Chinese', 'Math'],
              series: [
                { name: 'Series 1', data: [80, 50, 30, 40, 100, 20] },
                { name: 'Series 2', data: [20, 30, 40, 80, 20, 80] },
                { name: 'Series 3', data: [44, 76, 78, 13, 43, 10] },
              ],
            }}
          />
        </Grid>

        <Grid item xs={12} md={6} lg={8}>
          <AnalyticsNews title="News" list={_posts.slice(0, 5)} />
        </Grid>

        <Grid item xs={12} md={6} lg={4}>
          <AnalyticsOrderTimeline title="Order timeline" list={_timeline} />
        </Grid>

        <Grid item xs={12} md={6} lg={4}>
          <AnalyticsTrafficBySite
            title="Traffic by site"
            list={[
              { value: 'facebook', label: 'Facebook', total: 323234 },
              { value: 'google', label: 'Google', total: 341212 },
              { value: 'linkedin', label: 'Linkedin', total: 411213 },
              { value: 'twitter', label: 'Twitter', total: 443232 },
            ]}
          />
        </Grid>

        <Grid item xs={12} md={6} lg={8}>
          <AnalyticsTasks title="Tasks" list={_tasks} />
        </Grid>
      </Grid>
    </DashboardContent>
  );
}
